package com.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.result.Result;
import com.example.service.SmsService;
import com.example.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

import static com.example.utils.StringTools.getRandomNumber;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    private static final String HOST = "https://gyytz.market.alicloudapi.com";
    private static final String PATH = "/sms/smsSend";
    private static final String METHOD = "POST";
    private static final String APPCODE = "98a21e294304487d84138a22b11ccbaa";

    public Result sendVerificationCode(HttpSession session, String phoneNumber) {

        String RandCode = getRandomNumber(5);
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + APPCODE);

        Map<String, String> querys = new HashMap<>();
        querys.put("mobile", phoneNumber);
        querys.put("param", "**code**:" + RandCode + ",**minute**:5");  //设置有效期时间以及内容
        querys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");  //签名
        querys.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");   //内容模板

        Map<String, String> bodys = new HashMap<>();

        try {
            HttpResponse response = HttpUtils.doPost(HOST, PATH, METHOD, headers, querys, bodys);
            String responseBody = EntityUtils.toString(response.getEntity());
            System.out.println("responseBody" + responseBody); //打印相应内容
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 存储验证码到HttpSession中，假设设置的有效期为5分钟
                session.setAttribute("PhoneCode", RandCode);
                session.setMaxInactiveInterval(300); // 设置Session的有效期为300秒（5分钟）

                JSONObject jsonResponse = JSON.parseObject(responseBody);
                //String msg = jsonResponse.getString("msg");
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("res", "发送成功");
                dataMap.put("code", RandCode);
                System.out.println("发送验证码的session" + session);
                return Result.success(dataMap);
            } else {
                System.out.println("状态码" + statusCode);
                return Result.error("发送失败，状态码：" + statusCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("请求失败：" + e.getMessage());
        }
    }


}